﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace WebeTerm.Web.Controls
{
    public partial class PageControler : System.Web.UI.UserControl
    {
        public WebeTerm.Common.Pages PagesInfo { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SetPageInfo();
                setPageControler();
            }
        }

        public double getPagesCount()
        {
            double pagesCount = Math.Ceiling((double)PagesInfo.RecordSum / (double)PagesInfo.RecordPaginal);
            if (pagesCount == 0) return 1;
            return pagesCount;
        }

        public void SetPageInfo()
        {
            Info.InnerText = PagesInfo.PageNumber + "/" + PagesInfo.PageSum + "页" + PagesInfo.RecordSum + "条";
        }

        public void setPageControler()
        {
            int PageNo = PagesInfo.PageNumber;
            int PagesCount = PagesInfo.PageSum;

            //上一页

            HtmlAnchor prevPageLi = BuildPageButton("上一页", "PageChang(" + (PageNo - 1) + ",this);");
            Controler.Controls.Add(prevPageLi);

            //页码
            for (int i = 1; i <= PagesInfo.PageSum; i++)
            {
                HtmlAnchor toPageControl = null;
                if (i - PageNo == 0)
                    //当前页
                    toPageControl = BuildCurrentPageNumber(i.ToString());
                else if ((i >= PageNo - 1 && i <= PageNo - 0 + 1) || i == 1 || i == PagesCount)
                    //数字段
                    toPageControl = BuildPageButton(i.ToString(), "PageChang(" + i + ",this);");
                else if ((i - PageNo >= 1 || i - PageNo <= 1) && ((HtmlAnchor)Controler.Controls[Controler.Controls.Count - 1]).Attributes["tag"] != "[...]")
                {
                    //省略段
                    toPageControl = new HtmlAnchor();
                    toPageControl.InnerText = "[...]";
                    toPageControl.Attributes.Add("tag", "[...]");
                }

                if (toPageControl != null) Controler.Controls.Add(toPageControl);
            }
            HtmlAnchor nextPageLi = BuildPageButton("下一页", "PageChang(" + (PageNo + 1) + ",this);");
            Controler.Controls.Add(nextPageLi);
        }

        private HtmlAnchor BuildPageButton(string text, string clickScript)
        {
            HtmlAnchor a = new HtmlAnchor();
            a.InnerText = text;
            a.Attributes["onClick"] = clickScript;
            return a;
        }

        private HtmlAnchor BuildCurrentPageNumber(string text)
        {
            HtmlAnchor a = new HtmlAnchor();
            a.InnerText = text;
            a.Attributes["class"] = "cur";
            return a;
        }
    }
}